<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams">
      <el-form-item label="质控名称" prop="qcName">
        <el-input
          v-model="queryParams.qcName"
          clearable
          placeholder="请输入质控名称"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="质控状态" prop="qcState">
        <el-select
          v-model="queryParams.qcState"
          clearable
          placeholder="质控状态"
          size="small"
          style="width: 214px"
        >
          <el-option
            v-for="dict in qcStateOption"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开始日期" prop="startDate">
        <el-date-picker
          v-model="queryParams.startDateRange"
          :picker-options="pickerOptions"
          align="right"
          end-placeholder="结束日期"
          range-separator="至"
          start-placeholder="开始日期"
          type="daterange"
          value-format="yyyy-MM-dd HH:mm:ss"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['research:qualityControl:add']"
          icon="el-icon-plus"
          plain
          size="mini"
          type="primary"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['research:qualityControl:edit']"
          :disabled="single"
          icon="el-icon-edit"
          plain
          size="mini"
          type="success"
          @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['research:qualityControl:remove']"
          :disabled="multiple"
          icon="el-icon-delete"
          plain
          size="mini"
          type="danger"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="qualityControlList" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55"/>
      <el-table-column v-if="false" align="center" label="质控ID" prop="qcId"/>
      <el-table-column align="center" label="质控名称" prop="qcName"/>
      <el-table-column :show-overflow-tooltip="true" align="center" label="质控描述" prop="qcDesc" width="240"/>
      <el-table-column align="center" label="开始日期" prop="startDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="结束日期" prop="endDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" align="center" label="关闭原因" prop="closeReason" width="240"/>
      <el-table-column :formatter="qcStateFormat" align="center" label="质控状态" prop="qcState"/>
      <el-table-column :formatter="qcResultFormat" align="center" label="质控结果" prop="qcResult"/>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="350">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['research:qualityControl:edit']"
            icon="el-icon-edit"
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            v-hasPermi="['research:qualityControl:edit']"
            icon="el-icon-link"
            size="mini"
            type="text"
            @click="handleLinkEntry(scope.row)"
          >关联质控项
          </el-button>
          <el-button
            v-hasPermi="['research:qualityControl:edit']"
            icon="el-icon-paperclip"
            size="mini"
            type="text"
            @click="handleLinkSample(scope.row)"
          >关联样本
          </el-button>
          <el-button
            v-hasPermi="['research:qualityControl:query']"
            icon="el-icon-document"
            size="mini"
            type="text"
            @click="handleReport(scope.row)"
          >质控报告
          </el-button>
          <el-button
            v-hasPermi="['research:qualityControl:remove']"
            icon="el-icon-delete"
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :limit.sync="queryParams.pageSize"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改质控 对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="质控名称" prop="qcName">
          <el-input v-model="form.qcName" placeholder="请输入质控名称"/>
        </el-form-item>
        <el-form-item label="质控状态" prop="qcState">
          <el-select
            v-model="form.qcState"
            clearable
            placeholder="质控状态"
            size="small"
            style="width: 100%"
          >
            <el-option
              v-for="dict in qcStateOption"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="质控描述" prop="qcDesc">
          <el-input v-model="form.qcDesc" :rows="2" placeholder="请输入质控描述" type="textarea"/>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker v-model="form.startDate" clearable
                          placeholder="选择开始日期"
                          size="small"
                          style="width: 100%"
                          type="date"
                          value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker v-model="form.endDate" clearable
                          placeholder="选择结束日期"
                          size="small"
                          style="width: 100%"
                          type="date"
                          value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item v-if="form.qcState === '2'" label="关闭原因" prop="closeReason">
          <el-input v-model="form.closeReason" :rows="2" placeholder="请输入关闭原因" type="textarea"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="entryOpen" append-to-body title="关联质控条目" width="680px">
      <el-transfer v-model="entryValue" :data="entryData" :props="entryProps"></el-transfer>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEntry">确 定</el-button>
        <el-button @click="cancelEntry">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="report.open" append-to-body title="质控报告" width="980px">
      <div id="reportTable">
        <el-table :data="report.data" :span-method="objectSpanMethod" border style="width: 100%">
          <el-table-column :label="report.title" align="center">
            <el-table-column
              label="样本复份编号"
              prop="sampBackupCode"
            >
            </el-table-column>
            <el-table-column
              label="质控项"
              prop="qcEntryName"
              width="300"
            >
            </el-table-column>
            <el-table-column
              label="实际值"
              prop="qcEntryReal"
            >
            </el-table-column>
            <el-table-column
              label="预期值"
              prop="qcEntryExpect"
            >
            </el-table-column>
            <el-table-column
              :formatter="qcResultFormat"
              label="是否合格"
              prop="qcResult"
            >
            </el-table-column>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="printReport">打 印</el-button>
        <el-button @click="cancelReport">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addQualityControl,
  delQualityControl,
  getLinkEntryIds,
  getQualityControl,
  getReport,
  handleLinkEntry,
  listQualityControl,
  updateQualityControl
} from '@/api/research/qualityControl'
import { listAllEntry } from '@/api/research/qualityEntry'

export default {
  name: 'QualityControl',
  components: {},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 质控 表格数据
      qualityControlList: [],
      // 选中的质控项
      selectQualityControl: {},
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 质控状态
      qcStateOption: [],
      // 质控结果
      qcResultOption: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: 'createTime',
        isAsc: 'DESC',
        qcName: undefined,
        qcState: undefined,
        startDate: undefined
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      // 关联质控条目对话框
      entryOpen: false,
      // 选中的质控条目
      entryValue: [],
      // 质控条目列表
      entryData: [],
      entryProps: {
        key: 'qcEntryId',
        label: 'qcEntryName'
      },
      report: {
        title: '',
        open: false,
        data: [],
        spanArr: [],// 用于存放每一行记录的合并数
        passRate: 0// 合格率
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        qcName: [{ required: true, trigger: 'blur', message: '质控名称不能为空' }, {
          max: 60,
          trigger: 'blur',
          message: '质控名称不能超过60个字符'
        }],
        qcDesc: { max: 90, trigger: 'blur', message: '质控描述不能超过90个字符' },
        qcState: { required: true, trigger: 'change', message: '质控状态不能为空' }
      }
    }
  },
  created() {
    this.getDicts('quality_control_state').then(response => {
      this.qcStateOption = response.data
    })
    this.getDicts('quality_control_result').then(response => {
      this.qcResultOption = response.data
    })
    this.getList()
  },
  methods: {
    /** 查询质控 列表 */
    getList() {
      this.loading = true
      listQualityControl(this.queryParams).then(response => {
        this.qualityControlList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 质控报告按钮点击事件
    handleReport(row) {
      this.report.title = row.qcName
      this.report.data = []
      this.report.spanArr = []
      getReport(row.qcId).then(response => {
        this.report.open = true
        this.report.data = response.data
        this.judgeResult(this.report.data)
        this.getSpanArr(this.report.data)
      })
    },
    // 判断合格率
    judgeResult(data) {
      // let count = 0;
      // let pass = 0;
      // data.forEach(item => {
      //
      // })
    },
    // 判断合并行
    getSpanArr(data) {
      for (let i = 0; i < data.length; i++) {
        if (i === 0) {
          this.report.spanArr.push(1)
          this.pos = 0
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i].sampBackupCode === data[i - 1].sampBackupCode) {
            this.report.spanArr[this.pos] += 1
            this.report.spanArr.push(0)
          } else {
            this.report.spanArr.push(1)
            this.pos = i
          }
        }
      }
    },
    // 合并行
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        const _row = this.report.spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          // [0,0] 表示这一行不显示， [2,1]表示行的合并数
          rowspan: _row,
          colspan: _col
        }
      }
    },
    // 质控报告取消按钮点击事件
    cancelReport() {
      this.report.open = false
    },
    // 下载质控报告按钮点击事件
    printReport() {
      // let subOutPrint = document.getElementsByClassName("print");
      // let newContent = '';
      // for(let i = 0; i < subOutPrint.length; i++){
      //   let obj = subOutPrint[i].innerHTML;
      //   newContent += obj;
      // }
      // document.body.innerHTML = newContent;
      // window.print();
      // window.location.reload();
      let strBodyStyle = '<style>table, table tr, table th, table td { text-align: center; border: 1 solid #000000; border-collapse:collapse } table td { padding: 3px 0 } </style>'
      let strFormHtml = strBodyStyle + '<body>' + document.getElementById('reportTable').innerHTML + '</body>'
      this.$lodop.commonPrint(this.report.title, strFormHtml, 0, 'A4')
    },
    // 关联质控条目按钮点击事件
    handleLinkEntry(row) {
      this.selectQualityControl = row
      this.entryValue = []
      this.entryData = []
      this.entryOpen = true

      this.getAllEntryList()
      this.getLinkEntry(row.qcId)
    },
    // 关联样本按钮点击事件
    handleLinkSample(row) {
      this.$router.push({
        path: '/quality/QualitySample',
        query: {
          qcId: row.qcId
        }
      })
    },
    // 关联质控条目对话框确定事件
    submitEntry() {
      let qcEntryArr = []
      this.entryValue.forEach(item => {
        let qcEntry = {}
        qcEntry.qcId = this.selectQualityControl.qcId
        qcEntry.qcEntryId = item
        qcEntryArr.push(qcEntry)
      })
      handleLinkEntry(qcEntryArr).then(response => {
        this.$message.success('关联成功')
        this.entryOpen = false
      })
    },
    // 关联质控条目对话框取消事件
    cancelEntry() {
      this.entryOpen = false
    },
    // 获取已关联质控条目
    getLinkEntry(qcId) {
      getLinkEntryIds(qcId).then(response => {
        this.entryValue = response.data
      })
    },
    // 获取所有质控条目
    getAllEntryList() {
      listAllEntry().then(response => {
        this.entryData = response.data
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        qcId: undefined,
        qcName: undefined,
        qcDesc: undefined,
        qcState: undefined,
        startDate: undefined,
        endDate: undefined,
        closeReason: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.qcId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      if (this.qcStateOption && this.qcStateOption.length > 0) {
        this.form.qcState = this.qcStateOption[0].dictValue
      }
      this.open = true
      this.title = '添加质控 '
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const qcId = row.qcId || this.ids
      getQualityControl(qcId).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改质控 '
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.qcId != null) {
            updateQualityControl(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addQualityControl(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const qcIds = row.qcId || this.ids
      this.$confirm('是否确认删除质控 编号为"' + qcIds + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delQualityControl(qcIds)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },
    // 质量条目类型字典翻译
    qcStateFormat(row, column) {
      return this.selectDictLabel(this.qcStateOption, row.qcState)
    },
    // 质控结果类型字典翻译
    qcResultFormat(row, column) {
      return this.selectDictLabel(this.qcResultOption, row.qcResult)
    }
  }
}
</script>
